﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel; 
namespace Commerce.CSK.Web.Controls
{
    public partial class AddressControl : ItemViewControl
    {

        public string Legend { get; set; }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                if (ItemId == 0 && this.EditMode)
                {
                    _currentAddress = new Commerce.Data.Address();
                    
                    FillCurrentAddress(); 

                }
                else
                {
                    //TODO: Get the saved Address from the User Profile.
                }

            }
        }


        private Commerce.Data.Address _currentAddress;
        public Commerce.Data.Address CurrentAddress
        {
            get
            {
                return _currentAddress; 
            }
            set
            {
                _currentAddress = value;
                
                AddressView.DataSource = new List<Commerce.Data.Address>() { value };
                AddressView.DataBind(); 
                this.ItemId = _currentAddress.ID; 
                
            }
        }

        private void FillCurrentAddress()
        {
            //NOTE: This is an ugly hack. Need to figure a better
            //way to do this. 
            if (AddressView.Controls.Count > 0)
            {
                _currentAddress.FirstName = AddressView.FindControl("FirstName").ToString();
                _currentAddress.LastName = AddressView.FindControl("LastName").ToString();
                _currentAddress.Street1 = AddressView.FindControl("Street1").ToString();
                _currentAddress.Street2 = AddressView.FindControl("Street2").ToString();
                _currentAddress.City = AddressView.FindControl("City").ToString();
                _currentAddress.StateOrProvince = AddressView.FindControl("StateOrProvince").ToString();
                _currentAddress.Zip = AddressView.FindControl("Zip").ToString();
                _currentAddress.Country = AddressView.FindControl("Country").ToString();
                _currentAddress.Email = AddressView.FindControl("Email").ToString();
            }
        }


        [DefaultValue(false)]
        public bool EditMode {
            get
            {
                return AddressView.CurrentMode == FormViewMode.Edit; 
            }
            set
            {
                if (value)
                {
                    AddressView.ChangeMode(FormViewMode.Edit);
                }
                else
                {
                    AddressView.ChangeMode(FormViewMode.ReadOnly); 
                }
            }
        }
    }
}